package com.shiguiwu.springmybatis.websocket.server;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: server
 * @author: stone
 * @date: Created by 2022/3/14 19:53
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.websocket.server
 */

@Component
@Slf4j
@Service
@ServerEndpoint("/api/websocket/{userId}")
public class WebSocketServer {

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    private String userId;
    private Session session;

    //存放每个客户端对应的MyWebSocket对象
    //private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) throws IOException {


        this.session = session;

        this.userId = userId;
        //加入的客户端
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);

        }
        else {
            webSocketMap.put(userId, this);
            onlineCount.incrementAndGet();

        }

        //连接推送
        sendMessage("conn_success");
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());

    }

    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            onlineCount.decrementAndGet();

        }
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        if (StrUtil.isBlank(message)) {
            return;
        }

        //解析发送的报文
        JSONObject jsonObject = JSONUtil.parseObj(message);
        //追加发送人(防止串改)
        jsonObject.set("fromUserId", this.userId);

        String toUserId = jsonObject.getStr("toUserId");
        //传送给对应toUserId用户的websocket

        if (webSocketMap.containsKey(userId) && StrUtil.isNotBlank(toUserId)) {
            webSocketMap.get(toUserId).sendMessage(jsonObject.toString());
        }
        else {
            log.error("请求的userId:" + toUserId + "不在该服务器上");
            //否则不在这个服务器上，发送到mysql或者redis
        }

        log.info("服务端收到客户端：{} ；消息：{}", session.getId(), message);
        //session.getBasicRemote().sendText(message);

    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }


    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }


    //群发自定义消息
    public static void sendInfo(String message, @PathParam("userId") String userId) {
        log.info("推送消息到窗口" + userId + "，推送内容:" + message);

        if (StrUtil.isBlank(userId) || !webSocketMap.containsKey(userId)) {
            log.error("用户" + userId + ",不在线！或者消息为null");

        }

        Set<Map.Entry<String, WebSocketServer>> entries = webSocketMap.entrySet();
        for (Map.Entry<String, WebSocketServer> entry : entries) {
            try {
                //为null则全部推送
                if (userId == null) {
                    entry.getValue().sendMessage(message);
                    //推送给单个人
                } else if (entry.getKey().equals(userId)) {
                    entry.getValue().sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }

    }

    public static ConcurrentHashMap<String, WebSocketServer> getWebSocketMap() {
        return webSocketMap;
    }


}
